from flask  import Flask,Response,jsonify


# flask = werkzeug + sqlalchemy + jinja2

app = Flask(__name__)

# 将视图函数中返回的字典,转换成json对象,然后返回.
# restful-api
class JSONResponse(Response):

    @classmethod
    def force_type(cls,response, environ=None):
        """
        这个方法只有视图函数返回非字符,非元祖,非Response对象才会调用.
        response: 视图函数的返回值.
        """
        print(response)
        print(type(response))
        if isinstance(response,dict):
            # 1. jsonify除了将字典转换成json对象,还将该对象包装成一个Response对象.
            response = jsonify(response)
        return super(JSONResponse,cls).force_type(response,environ)
        # return Response('hello')

app.response_class = JSONResponse

@app.route('/')
def Index():
    # Response('欢迎来到我的首页',status=200,mimetype='text/html')
    return '欢迎来到我的首页'

@app.route('/list1/')
def list1():
    # return {'username':'Jacky Yuan'}
    # return Response('list1')
    resp = Response('list1')
    resp.set_cookie('country','china')
    return resp 

@app.route('/list2/')
def list2():
    return 'list2',200,{'X-NAME':'Jacky'}

@app.route('/list3/')
def list3():
    return {'username':'Jacky','age':18}

if __name__ == "__main__":
    app.run(debug=True, host='0.0.0.0')